package com.yao.handler;

import com.alibaba.fastjson.JSONObject;
import com.yao.bean.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/3 22:01
 * FileName: GlobalExceptionHandler
 * Description:
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R handle(Exception e){
        return R.err();
    }

    @ExceptionHandler(AccessDeniedException.class)
    public R handle(){

        R r = new R();
        r.setCode(401);
        r.setData("权限不足");
        r.setMsg("权限不足");
       return r;

    }

    @ExceptionHandler(AuthenticationException.class)
    public R handle(AuthenticationException authException){
        R r = new R();
        r.setCode(455);
        if(authException instanceof UsernameNotFoundException){
            r.setData("");
            r.setMsg(authException.getMessage());
        }

        if(authException instanceof InsufficientAuthenticationException){
            InsufficientAuthenticationException ae= (InsufficientAuthenticationException) authException;
            System.out.println("authException:"+authException);
            r.setData(authException);
            Throwable cause = authException.getCause();

            OAuth2Exception e=null;
            if(cause instanceof OAuth2Exception) e = (OAuth2Exception) cause;
            r.setMsg(e.getMessage());
            r.setData(e.getOAuth2ErrorCode());
        }

        return r;

    }

    @ExceptionHandler(BadCredentialsException.class)
    public R handle(BadCredentialsException badCredentialsException){
        R r = R.err();
        BadClientCredentialsException credentialsException= (BadClientCredentialsException) badCredentialsException.getCause();
        r.setData(credentialsException.getOAuth2ErrorCode());
        r.setMsg("用户名密码错误");
        return r;
    }
}
